package com.smt.modules.bus.service.impl;

import com.smt.common.enums.Code;
import com.smt.common.utils.*;
import com.smt.modules.app.utils.CurrentDayRewardUtil;
import com.smt.modules.bus.entity.*;
import com.smt.modules.bus.service.*;
import com.smt.modules.bus.vo.ProjectTaskVo;
import com.smt.modules.bus.vo.SubtaskVo;
import org.joda.time.DateTime;
import org.joda.time.Days;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Map;

import com.baomidou.mybatisplus.mapper.EntityWrapper;
import com.baomidou.mybatisplus.plugins.Page;
import com.baomidou.mybatisplus.service.impl.ServiceImpl;

import com.smt.modules.bus.dao.SubtaskDao;

import static com.alibaba.druid.sql.visitor.SQLEvalVisitorUtils.eq;
import static com.alibaba.druid.sql.visitor.SQLEvalVisitorUtils.sub;


@Service("subtaskService")
public class SubtaskServiceImpl extends ServiceImpl<SubtaskDao, SubtaskEntity> implements SubtaskService {

    @Autowired
    private ProjectService projectService;
    @Autowired
    private CurrentDayRewardUtil currentDayRewardUtil;
    @Autowired
    private ScheduleService scheduleService;
    @Autowired
    private ProjectTaskService projectTaskService;

    @Autowired
    private AttachmentService attachmentService;

    @Override
    public PageUtils queryPage(Map<String, Object> params) {
        Page<SubtaskEntity> page = this.selectPage(
                new Query<SubtaskEntity>(params).getPage(),
                new EntityWrapper<SubtaskEntity>()
        );

        return new PageUtils(page);
    }

    /**
     * 获取子任务集合
     *
     * @param taskId
     * @return
     */
    @Override
    public R getSubTaskList(Long taskId) {
        List<SubtaskEntity> subTaskList = baseMapper.getSubTaskList(taskId);
        Date localTime = new DateTime().withTimeAtStartOfDay().toLocalDateTime().toDate();
        DateTime nowTime = new DateTime(localTime);
        subTaskList.stream()
                .forEach(s -> {
                    if (s.getStartTime() == null || s.getEndTime() == null) {
                        s.setDays(Integer.MAX_VALUE);
                    } else {
                        DateTime dateTime = new DateTime(s.getEndTime());
                        int days = Days.daysBetween(nowTime, dateTime).getDays();
                        s.setDays(days);
                        //将当前显示被删除的成员清空
                        if (s.getMemberExist() == 1) {
                            s.setMemberId(null);
                        }
                    }
                    //添加文件状态信息
                    List<AttachmentEntity> attachmentEntity = attachmentService.selectList(new EntityWrapper<AttachmentEntity>()
                            .eq("project_sub_task_id", s.getId())
                            .orderBy("create_time", false));
                    if (null != attachmentEntity && attachmentEntity.size() != 0) {
                        s.setHaveFile(1);
                        String fileName = attachmentEntity.get(0).getFileName();
                        fileName = fileName.substring(Constant.FILE_TOKEN.length() + 1, fileName.length());
                        s.setFileName(fileName);
                    } else {
                        s.setHaveFile(0);
                    }
                });
        return R.ok().put("taskId", subTaskList);
    }

    /**
     * 修改子任务
     *
     * @param subtaskVo
     * @return
     */
    @Override
    public R editTask(SubtaskVo subtaskVo, Long userId) {
        //自己申请完成
        if (subtaskVo.getStatus().equals(50) && userId.equals(subtaskVo.getMemberId())) {
            SubtaskEntity subtaskEntity = subtaskVo.copyPropertiesTo(new SubtaskEntity());
            BeanUtils.copyProperties(subtaskVo, subtaskEntity);
            subtaskEntity.setMemberExist(0);
            boolean b = updateById(subtaskEntity);
            return b ? R.ok("子任务成功完成") : R.error(EnumToKeyUtil.toInt(Code.MODIFY_DATA_ERROR), "子任务完成失败");
        }
        Long subTaskId = subtaskVo.getId();
        //任务id
        Long projectTaskId = subtaskVo.getProjectTaskId();
        ProjectTaskEntity projectTaskEntity = projectTaskService.selectById(projectTaskId);
        Long projectId = projectTaskEntity.getProjectId();
        ProjectEntity projectEntity = projectService.selectById(projectId);
        SubtaskEntity subtaskEntity = new SubtaskEntity();

        //要想操作此子任务，需要判断项目不能为空，而且其父辈任务，阶段负责人，创建者都可以修改此子任务
        if (projectEntity != null &&
                (projectTaskEntity.getMemberId().equals(userId) ||
                        projectTaskEntity.getStageMemberId().equals(userId)) ||
                projectEntity.getCreatedId().equals(userId)) {

            DateTime endTime = new DateTime(subtaskVo.getEndTime());
            //此时应该是子任务被上级确认完成
            Integer status1 = subtaskVo.getStatus();
            if (endTime != null && null != status1 && status1.equals(1)) {
                Integer status = subtaskVo.getStatus();
                if (status != null && status.equals(2)) {
                    subtaskVo.setStatus(1);
                }
            }
            BeanUtils.copyProperties(subtaskVo, subtaskEntity);
            subtaskEntity.setMemberExist(0);
            boolean b = updateById(subtaskEntity);
            //添加日程
            if (subTaskId != null && subtaskVo.getEndTime() != null) {
                scheduleService.addScheduleInfo(subtaskVo);
            }
            if (subtaskVo.getStatus() != null && subtaskVo.getStatus().equals(3)) {
                ScheduleEntity scheduleEntity = new ScheduleEntity();
                scheduleEntity.setPrior(-1);
                scheduleService.update(scheduleEntity, new EntityWrapper<ScheduleEntity>()
                        .eq("sub_task_id", subTaskId));
            }
            return b ? R.ok("子任务修改成功") : R.error(EnumToKeyUtil.toInt(Code.MODIFY_DATA_ERROR), "子任务修改失败");
        } else {
            return R.error(EnumToKeyUtil.toInt(Code.MISSING_PERMISSION), "您的权限不够，无法修改");
        }
    }


    /**
     * 创建子任务
     *
     * @param subtask
     * @param userId
     * @return
     */
    @Override
    public R createSubTask(SubtaskVo subtask, Long userId) {
        subtask.setCreateTime(DateTime.now().toDate());
        subtask.setUpdateTime(DateTime.now().toDate());
        subtask.setStatus(0);
        boolean in = insert(subtask.copyPropertiesTo(new SubtaskEntity()));
        if (in) {
            currentDayRewardUtil.issueRewards(Constant.DAY_2, userId);
            //检测任务状态 创建子任务时候，如果任务是完成状态，将此时的任务状态转换成未完成状态 睿智需求。。。
            Long projectTaskId = subtask.getProjectTaskId();
            ProjectTaskEntity projectTaskEntity = projectTaskService.selectOne(new EntityWrapper<ProjectTaskEntity>()
                    .eq("id", projectTaskId));
            projectTaskEntity.setStatus(0);
            projectTaskService.updateById(projectTaskEntity);
        }
        return in ? R.ok("创建任务成功") : R.error(EnumToKeyUtil.toInt(Code.APPEND_DATA_ERROR), "创建任务失败");
    }
}
